<template>
	<div>
		<MkBillPanel :bill="ctx.zhuBiao" ref='billPanelRef' printCode='traLinChuangFaXue'>
			<template #button>
				<MkButtonEdit @click="newEntity" :isEdit="isCanEdit" />

				<MkButtonSubmit @click="submit" :loading="ctx.loading" :isEdit="ctx.isEdit" />
				<MkButtonMore>
					<a-menu-item @click="cancel">作废</a-menu-item>
					<a-menu-item @click="history">操作记录</a-menu-item>
				</MkButtonMore>
				<MkButtonMore title="打印" @click="print" icon="ele-Printer">
					<a-menu-item @click="print">打印</a-menu-item>
				</MkButtonMore>
			</template>
			<template #info>
				<MkForm :col="4" v-model="ctx.zhuBiao">
					<MkSelectUser label='发血人' v-model='ctx.zhuBiao.faXueRenId' prop='faXueRenId' :isEdit='ctx.isEdit' />
					<!-- scope="ShuXueKe" /> -->
					<MkSelectUser label='取血人' v-model='ctx.zhuBiao.quXueRenId' prop='quXueRenId' :isEdit='ctx.isEdit' />
					<MkInput v-model="ctx.zhuBiao.remark" label="备注" :isEdit='ctx.isEdit' :col="2" />
				</MkForm>
			</template>
			<!-- 单据信息 -->
			<div class="edit-container">
				<MkPanel>
					<!-- 扫码框 -->
					<MkXueYeScanInput @onEnter="scanCodeOut" placeholder="发血扫码" ref="scanRef" width="300px" v-if="ctx.isEdit" />
					<MkXueYeScanInput @onEnter="scanCodeNurse" placeholder="护士扫码" ref="scanRef" width="300px" v-if="ctx.isEdit" />
					<!-- 明细列表 -->
					<MkTable :data="ctx.mingXiTable">
						<MkColumn label="发血" prop="faXue" />
						<MkColumn label="取血" prop="quXue" />
						<el-table-column label="血液产品名称 / 献血码 / 产品码 / 血型 / 容量 / 失效日期" min-width="480px">
							<template #default="{ row }">{{ getBloodData(row) }}</template>
						</el-table-column>
						<MkColumn label="配血结果" prop="peiXueJieGuo" />
						<MkColumn label="接收人" prop="jieShouUser" />
						<MkColumn label="接收时间" prop="jieShouTime" />
					</MkTable>
				</MkPanel>
			</div>
		</MkBillPanel>
		<List @load="loadEntity" ref="listRef" :parentWidth="setupContainerWidthLogic" />
	</div>
</template>
<script lang="ts" setup name="traLinChuangFaXue">
// 临床发血模块
// 导入工具函数，包括判断空值、显示成功提示、显示失败提示
import { isNull, showSuccess, showError } from '/@/utils';
// 历史单据列表组件
import List from './list.vue';
// 导入血液入库单相关的 API 和输出类型
import { TraFaXueApi, TraFaXueOutput, TraFaXueMingXiOutput, FaXueAddInput } from '/@/api/tra/TraFaXue';
import { InvKuCunOutput } from '/@/api/inv/InvKuCun';
import { TraShenQingDanOutput } from '/@/api/tra/TraShenQing/dto/TraShenQingDanOutput';
// export const formRef = ref();
// 临床发血模块--编辑
/**
 * 组件实例
 */
const listRef = ref();
/**
 * 定义 props 类型，需要同步写入props的类型
 */
// const ctxProps: Ref<{ shenQingDanInfo?: TraShenQingDanOutput }> = ref({});
// props在vue文件声明后才能传到ts文件
const props = defineProps({
	shenQingDanInfo: {
		type: Object as PropType<TraShenQingDanOutput>,
		default: () => { },
	},
});
watch(() => props.shenQingDanInfo, (oldVal, newVal) => {
	if (isNull(newVal.traShenQing?.id)) return;
	loadEntity({ id: newVal.traShenQing?.id } as TraFaXueOutput);
}, { deep: true });
/**
* 打开历史记录
*/
const openDrawer = () => {
	console.log('打开历史记录leqaqin', listRef.value);
	// 使用可选链操作符 ?. 确保 drawerRef.value 存在且 open 方法存在才调用
	listRef.value?.open();
};

/**
 * 初始化上下文对象
 * @returns 包含初始状态的上下文对象
 */
const initCtx = () => ({
	// 标识是否处于编辑状态
	isEdit: false,
	// 标识是否正在加载数据
	loading: false,
	// 主表数据，默认单据类型为交叉配血
	zhuBiao: { danJuLeiXing: '临床发血' } as TraFaXueOutput,
	// 明细表格数据
	mingXiTable: [] as TraFaXueMingXiOutput[],
});

// 使用 reactive 初始化响应式上下文对象
const ctx = reactive(initCtx());
const emits = defineEmits(['submitCallBack'])
//  ============================================= 主表 ====================================
// 是否可编辑
const isCanEdit = computed(() => {
	return props.shenQingDanInfo.traShenQing.id && !ctx.zhuBiao.id
})
/**
 * 清空表单数据，初始化实体
 */
const newEntity = () => {
	// 将上下文对象重置为初始状态
	Object.assign(ctx, initCtx());
	// 设置为编辑状态
	ctx.isEdit = true;
	// 让扫码框获得焦点
};

/**
 * 列表 -- 查看按钮的处理函数，加载实体数据
 * @param zhuBiao 主表数据
 */
const loadEntity = (zhuBiao: TraFaXueOutput) => {
	console.log("loadEntity", zhuBiao);
	// 检查主表数据或其 ID 是否为空，若为空则直接返回
	if (isNull(zhuBiao) || isNull(zhuBiao.id)) {
		return;
	}
	newEntity();
	// 调用库存入库 API 的 get 方法获取数据
	TraFaXueApi.getMeesage(zhuBiao.id).then((res) => {
		if (isNull(res.zhuBiao?.id)) return;
		// 重置表单字段
		// formRef.value.resetFields();
		// 将获取到的主表数据赋值给上下文对象的主表属性
		ctx.zhuBiao = Object.assign({}, res.zhuBiao);
		// 将获取到的明细列表数据赋值给上下文对象的明细表格属性
		ctx.mingXiTable = Object.assign([], res.mingXiList);
		// 设置为非编辑状态
		ctx.isEdit = false;
	});
};
defineExpose({ loadEntity })
/**
 * 提交
 */
const submit = () => {
	if (!props.shenQingDanInfo || !props.shenQingDanInfo.traShenQing.id) {
		showError('请选择申请单！');
		return;
	}
	if (ctx.mingXiTable.length == 0) {
		showError('请添加发血血液！');
		return;
	}
	let input = {} as FaXueAddInput;
	input.zhuBiao = Object.assign({}, ctx.zhuBiao);
	input.zhuBiao.traShenQingId = props.shenQingDanInfo.traShenQing.id;
	input.mingXiList = Object.assign([], ctx.mingXiTable);
	TraFaXueApi.add(input)
		.then((res) => {
			showSuccess();
			loadEntity(res);
			emits('submitCallBack', res.id)
		})
}
/**
 * 作废
 */
const cancel = () => {
}
/**
 * 操作记录
 */
const history = () => {
}
/**
 * 打印
 */
const print = () => {
}
/**
 * 发血扫码
 */
const scanCodeOut = (scanResult: InvKuCunOutput) => {
	console.log("scanCodeOut", scanResult);
	if (ctx.mingXiTable.some((e) => e.xueYeId === scanResult.id)) {
		showError("列表中已有该血液");
		return;
	}
	ctx.mingXiTable.push({
		xueYeId: scanResult.id,
		invKuCun: scanResult
	} as TraFaXueMingXiOutput)
}
/**
 * 取血扫码
 */
const scanCodeNurse = (scanResult: any) => {

}
/**
 * 整合信息显示
 * 血液产品名称/献血码/产品码/血型/容量/失效日期
 */
const getBloodData = (row: TraFaXueMingXiOutput) => {
	let { id, mingCheng, chanPinId, xianXueMa, abo, rhD, rongLiang, danWei, shiXiaoShiJian } = row.invKuCun;
	if (id == 0) {
		return '';
	}
	return `${mingCheng} / ${xianXueMa} / ${chanPinId} / ${abo}${rhD} / ${rongLiang}${danWei} / ${shiXiaoShiJian}`;
}

/**
 * 工具类，这是给抽屉长度的
 */
const containerRef = ref<HTMLElement | null>(null);
const containerWidth = ref(0);

const setupContainerWidthLogic = () => {
	const updateContainerWidth = () => {
		console.log("containerRef.value", containerRef.value);
		if (containerRef.value != null) {
			containerWidth.value = containerRef.value.offsetWidth;
		}
	};

	onMounted(() => {
		updateContainerWidth();
		window.addEventListener('resize', updateContainerWidth);
	});

	onUnmounted(() => {
		window.removeEventListener('resize', updateContainerWidth);
	});
}
</script>
<style lang="scss" scoped>
.tra-lin-chuang-fa-xue-edit {
	height: 100%;
	display: flex;
	flex-direction: column;

	.edit-bill {
		flex-shrink: 0;
	}

	.edit-container {
		display: flex;
		flex-direction: column;
		flex: 1;
		margin-top: 0.5rem;
	}
}
</style>
